package cn.mandifal.seller.service.impl;

import cn.mandifal.mapper.DpSellerMapper;
import cn.mandifal.pojo.DpSeller;
import cn.mandifal.pojo.DpSellerExample;
import cn.mandifal.seller.service.SellerService;
import cn.mandifal.utils.EmailUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 商家服务 实现层
 * @author ws
 */
@Service(timeout = 3000)
public class SellerServiceImpl implements SellerService {
    @Autowired
    private DpSellerMapper dpSellerMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addSeller(DpSeller seller) {
        seller.setStatus("0");
        seller.setCreateTime(new Date());
        dpSellerMapper.insert(seller);
    }

    @Override
    public DpSeller findOneSeller(String id) {
        return dpSellerMapper.selectByPrimaryKey(id);

    }

    @Override
    public void updateSellerInfo(DpSeller dpSeller) {
        dpSeller.setUpdateTime(new Date());
        dpSellerMapper.updateByPrimaryKey(dpSeller);
    }

    @Override
    public DpSeller findSeller(String id, String email) {
        DpSellerExample example=new DpSellerExample();
        DpSellerExample.Criteria criteria = example.createCriteria();
        criteria.andSellerIdEqualTo(id);
        criteria.andEmailEqualTo(email);
        List<DpSeller> dpSellers = dpSellerMapper.selectByExample(example);
        return dpSellers.get(0);
    }

    /**
     * 创造验证码并发送
     * @param email 要发送的邮箱
     */
    @Override
    public void createCode(String email){
        //得到6 位随机数字
        String code = EmailUtil.achieveCode();
        //存入 redis 以 email 为 key，
        redisTemplate.opsForValue().set(email,code,1800L,TimeUnit.SECONDS);
        //发送邮箱验证码
        EmailUtil.sendAuthCodeEmail(email,code);
    }
    @Override
    public Boolean checkCode(String email,String code){
        String codeFromRedis = (String) redisTemplate.opsForValue().get(email);
        if (codeFromRedis != null){
            if (codeFromRedis.equals(code)){
                return true;
            }
        }
        return false;
    }
}
